/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManFactura.java
 *
 * Created on 25/02/2011, 01:44:55 AM
 */

package com.catosist.run.application.viaje.factura;

import com.catosist.run.application.Util.ButtonTabComponent;
import com.catosist.run.business.gestorcomprobante.GestorComprobante;
import com.catosist.run.business.gestorviaje.GestorViaje;
import com.catosist.run.services.ComprobanteDTO;
import com.catosist.run.services.ViajeDTO;
import java.util.Iterator;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author igorov
 */
public class ManFactura extends javax.swing.JFrame {

    /** Creates new form ManFactura */
    public ManFactura() {
        initComponents();
    }

    public ManFactura(int viajeId, GestorViaje gestorViaje) {
        initComponents();
        this.viajeId = viajeId;
        this.gestorViaje = gestorViaje;
        

        iniciar();
        refresh();
    }

    public JPanel getPanel() {
        return this.jPanel1;
    }

    private void iniciar() {
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorComprobante = (GestorComprobante) ctx.getBean("gestorComprobante");

    }

    public void refresh() {

        ViajeDTO viajeDTO = gestorViaje.getById(viajeId);

//        System.out.println("Viaje seleccionado: " + viajeDTO.getnRuta());
//
        this.lblTitle.setText("Factura del viaje:     fecha: " + viajeDTO.getFingreso()
                + "             Ruta: " + viajeDTO.getnRuta()
                + "             Chofer: " + viajeDTO.getnPersona()
                + "             Adelanto: " + viajeDTO.getAdelanto());
//
        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("ID");
        model.addColumn("Factura No");
        model.addColumn("Nombre");
        model.addColumn("Fecha");
        model.addColumn("Total");
        System.out.println("REFRESH");
//
//        float total = 0f;
        List<ComprobanteDTO> comprobanteDTOs = gestorComprobante.getByViajeId(viajeId);
        if(comprobanteDTOs == null)
            System.out.println("Comprobantes nulos");
        System.out.println("cantidad de comprobantes: " + comprobanteDTOs.size()+" del viaje "+viajeId);
        for (Iterator<ComprobanteDTO> it = comprobanteDTOs.iterator(); it.hasNext();) {
            ComprobanteDTO comprobanteDTO = it.next();
            model.addRow(comprobanteDTO.toArray());
//            total += comprobanteDTO.getTotal();
        }
        this.jTable1.setModel(model);
//        this.lblTotal.setText("Total: " +String.valueOf(total));

//        this.jTable1.getColumnModel().getColumn(3).setPreferredWidth(400);
    }

    public void agregaPestanha(JPanel panel, String titulo) {
        this.tabWork.add(titulo, panel);
        this.tabWork.setSelectedIndex(this.tabWork.getTabCount() - 1);
        ButtonTabComponent pestana = new ButtonTabComponent("nano", this.tabWork);
        this.tabWork.setTabComponentAt(this.tabWork.getTabCount() - 1, pestana);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnDetalles = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        lblTitle = new javax.swing.JLabel();
        tabWork = new javax.swing.JTabbedPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.catosist.run.application.desktopapplication.DesktopApplication.class).getContext().getResourceMap(ManFactura.class);
        btnDetalles.setText(resourceMap.getString("btnDetalles.text")); // NOI18N
        btnDetalles.setName("btnDetalles"); // NOI18N
        btnDetalles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetallesActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        lblTitle.setFont(resourceMap.getFont("lblTitle.font")); // NOI18N
        lblTitle.setText(resourceMap.getString("lblTitle.text")); // NOI18N
        lblTitle.setName("lblTitle"); // NOI18N

        tabWork.setName("tabWork"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(lblTitle))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 556, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnDetalles))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tabWork, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tabWork, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnDetalles)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnDetallesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetallesActionPerformed
        // TODO add your handling code here:
        try {
            int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());
            FacturaDetalles facturaDetalles = new FacturaDetalles(gestorComprobante, i , viajeId, this);
//            facturaDetalles.setVisible(true);
            agregaPestanha(facturaDetalles.getPanel(), "Facturas");
            refresh();
        } catch (Exception e) {
            System.out.println("Excepcion: " + e.getMessage());
            JOptionPane.showMessageDialog(this, "Debe seleccionar una factura existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }

    }//GEN-LAST:event_btnDetallesActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ManFactura().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDetalles;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JTabbedPane tabWork;
    // End of variables declaration//GEN-END:variables
    private int viajeId;
    private GestorViaje gestorViaje;
    private ApplicationContext ctx;
    private GestorComprobante gestorComprobante;
}
